/**
 * File    : OpenIDAuthRequest.java
 * Created : 2008-10-5
 * By      : LuHuiguo
 */
package com.luhuiguo.sso.provider;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;

import org.openid4java.message.AuthRequest;
import org.openid4java.message.MessageException;
import org.openid4java.message.MessageExtension;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.sreg.SRegMessage;
import org.openid4java.message.sreg.SRegRequest;
import org.openid4java.server.RealmVerifier;

/**
 * @author LuHuiguo
 * @version $Id: OpenIDAuthRequest.java 7 2008-10-06 03:46:38Z LuHuiguo $
 * 
 */
public class OpenIDAuthRequest implements Serializable {

	private static final long serialVersionUID = -851408400405381258L;

	private ParameterList requestParameters;
	private FetchRequest fetchRequest;
	private SRegRequest sregRequest;
	private AuthRequest authReq;

	public OpenIDAuthRequest(ParameterList requestParameters,
			RealmVerifier realmVerifier) throws MalformedOpenIDRequestException {
		this.requestParameters = requestParameters;
		try {
			authReq = AuthRequest.createAuthRequest(requestParameters,
					realmVerifier);
		} catch (MessageException e) {
			throw new MalformedOpenIDRequestException(
					"AuthRequest could not be reconstructed from RequestParamaters",
					e);
		}
		try {
			if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
				MessageExtension ext = authReq
						.getExtension(AxMessage.OPENID_NS_AX);
				if (ext instanceof FetchRequest)
					fetchRequest = (FetchRequest) ext;
			}
		} catch (MessageException e) {
		}
		try {
			if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG)) {
				MessageExtension ext = authReq
						.getExtension(SRegMessage.OPENID_NS_SREG);
				if (ext instanceof SRegRequest)
					sregRequest = (SRegRequest) ext;
			}
		} catch (MessageException e) {
		}
	}

	public ParameterList getParamaterList() {
		return requestParameters;
	}

	public FetchRequest getFetchRequest() {
		return fetchRequest;
	}

	public SRegRequest getSRegRequest() {
		return sregRequest;
	}

	public String getIdentifier() {
		return authReq.getIdentity();
	}

	public String getReturnToURL() {
		return authReq.getRealm();
	}

	@SuppressWarnings("unchecked")
	public Collection getRequiredAttributes() {
		if (sregRequest != null)
			return sregRequest.getAttributes(true);
		else
			return Collections.EMPTY_LIST;
	}

	@SuppressWarnings("unchecked")
	public Collection getOptionalAttributes() {
		if (sregRequest != null)
			return sregRequest.getAttributes(false);
		else
			return Collections.EMPTY_LIST;
	}

	public boolean hasAssocHandle() {
		return requestParameters.hasParameter("openid.assoc_handle");
	}
}
